//
//  QQGroupProViewController.m
//  sdkDemo
//
//  Created by Zhe Wang on 2021/5/10.
//  Copyright © 2021 qqconnect. All rights reserved.
//

#import "QQGroupProViewController.h"
#import <TencentOpenAPI/TencentOAuth.h>
#if !QQ_OPEN_SDK_LITE
#import <TencentOpenAPI/TencentOAuth+Full.h>
#endif
#import <TencentOpenAPI/QQApiInterface.h>
#if !QQ_OPEN_SDK_LITE
#import "TencentOpenAPI/QQApiInterfaceObject+Full.h"
#endif

#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import "SDKCall.h"


#if !QQ_OPEN_SDK_LITE

@implementation QQGroupProViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)doCreateQQGroupPro:(QElement *)sender {
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    if (![self checkDataValid]){
        return;
    }
    
    NSString *url = @"https://qq-web.cdn-go.cn/qun.qq.com_pro/9010b6cd/app/create/dist/cdn/assets/images/default.png";
    QQApiCreateQQGroupProObject *createGroupProObject = [[QQApiCreateQQGroupProObject alloc] init];
    createGroupProObject.from = self.from_input;
    createGroupProObject.openid = [[TencentOAuth sharedInstance] getCachedOpenID];
    createGroupProObject.guild_id = self.guild_id_input;
    createGroupProObject.zone_id = self.zone_id_input;
    createGroupProObject.guild_name = self.guild_name_input;
    createGroupProObject.guild_avatar = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
    createGroupProObject.roleid = self.roleid_input;
    createGroupProObject.areaid = @"游戏大区ID";
    createGroupProObject.user_zone_id = self.user_zone_id_input;
    createGroupProObject.user_label = self.user_label_input;
    createGroupProObject.nick_name = self.nick_name_input;
    createGroupProObject.force_account_equal = self.force_account_equal_input ? @"1" : @"0";
    createGroupProObject.signKey = self.app_key_input;
    createGroupProObject.openKey = [[TencentOAuth sharedInstance] getCachedToken];
    if (self.specify_uin_input.length != 0) {
        createGroupProObject.specify_uin = self.specify_uin_input;
    }
    
    SendMessageToQQReq *sendMessageRequest = [SendMessageToQQReq reqWithContent:createGroupProObject];
    [QQApiInterface sendMessageToCreateQQGroupProWithMessageRequest:sendMessageRequest sendResultBlock:^(QQApiSendResultCode sendResultCode, NSString *message) {
        [self handleSendResult:sendResultCode message:message];
    }];
}

- (void)doJoinQQGroupPro:(QElement *)sender {
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    if (![self checkDataValid]) {
        return;
    }
    
    QQApiJoinQQGroupProObject *joinGroupProObject = [[QQApiJoinQQGroupProObject alloc] init];
    joinGroupProObject.from = self.from_input;
    joinGroupProObject.openid = [[TencentOAuth sharedInstance] getCachedOpenID];
    joinGroupProObject.guild_id = self.guild_id_input;
    joinGroupProObject.zone_id = self.zone_id_input;
    joinGroupProObject.force_account_equal = self.force_account_equal_input ? @"1" : @"0";
    joinGroupProObject.signKey = self.app_key_input;
    joinGroupProObject.openKey = [[TencentOAuth sharedInstance] getCachedToken];
    if (self.specify_uin_input.length != 0) {
        joinGroupProObject.specify_uin = self.specify_uin_input;
    }
    
    SendMessageToQQReq *sendMessageRequest = [SendMessageToQQReq reqWithContent:joinGroupProObject];
    [QQApiInterface sendMessageToJoinQQGroupProWithMessageRequest:sendMessageRequest sendResultBlock:^(QQApiSendResultCode sendResultCode, NSString *message) {
        [self handleSendResult:sendResultCode message:message];
    }];
}

- (void)doCheckQQGroupPro:(QElement *)sender {
    
    [self.root fetchValueUsingBindingsIntoObject:self];
    
    if (![self checkDataValid]){
        return;
    }
    
    [self requestGuildOpenIDWithCompletion:^(NSDictionary *retDict) {
        NSString *message = retDict.description;
        NSLog(@"%@", message);
        [self showAlertViewWithTitle:@"查询结果" Message:message];
        if ([retDict[@"msg"] isEqual:@"success"]) {
            // retDict[@"data"][@"bind_info"][0][@"open_id"]
            QEntryElement *element = ((QEntryElement *)[self.root elementWithKey:@"guild_openid"]);
            // 如果guild_openid正在输入，先刷新一遍可以释放键盘，避免数据不刷新的问题。
            [self.quickDialogTableView reloadCellForElements:element, nil];
            element.textValue = (NSString *)retDict[@"data"][@"bind_info"][0][@"open_id"];
            [self.quickDialogTableView reloadCellForElements:element, nil];
        }
    }];
}

- (void)showAlertViewWithTitle:(NSString *)title Message:(NSString *)message {
    NSAssert([NSThread isMainThread], @"UI操作必须在主线程");
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"频道结果"
                                                    message:message
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

- (void)requestGuildOpenIDWithCompletion:(void(^)(NSDictionary *retDict))completion {
    QQApiQueryQQGroupProInfoObject *queryGroupProInfoObject = [[QQApiQueryQQGroupProInfoObject alloc] init];
    queryGroupProInfoObject.org_id = self.guild_id_input;
    queryGroupProInfoObject.world_id = self.zone_id_input;
    queryGroupProInfoObject.openID = [[TencentOAuth sharedInstance] getCachedOpenID];
    queryGroupProInfoObject.openKey = [[TencentOAuth sharedInstance] getCachedToken];
    
    SendMessageToQQReq *sendMessageRequest = [SendMessageToQQReq reqWithContent:queryGroupProInfoObject];
    
    [QQApiInterface sendQueryQQGroupProInfo:sendMessageRequest resultBlock:^(NSDictionary *result) {
        NSLog(@"%s, %@", __func__, result);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion) {
                completion(result);
            }
        });
    }];
}

- (BOOL)checkDataValid {
    if (self.from_input.length == 0 || self.guild_id_input.length == 0) {
        [self showAlertViewWithTitle:@"参数错误" Message:@"请检查必填参数"];
        return NO;
    }
    
    if (![[TencentOAuth sharedInstance] isSessionValid]) {
        [self showAlertViewWithTitle:@"登录态已过期" Message:@"请重新登录"];
        return NO;
    }
    
    return YES;
}

- (void)handleSendResult:(QQApiSendResultCode)sendResult message:(NSString *)message {
    if (message && message.length > 0) {
        UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
        [msgbox show];
        return;
    }
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"App未注册" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"API接口不支持" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPISENDFAILD:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIVERSIONNEEDUPDATE:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"当前QQ版本太低，需要更新" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"缺少必要参数" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        default:
        {
            break;
        }
    }
}

@end
#endif
